package com.jcl.recruit.api.wechat.controller;

import com.jcl.core.resp.ApiResponse;
import com.jcl.core.security.SecurityUtils;
import com.jcl.core.security.UserToken;
import com.jcl.core.utils.StringUtils;
import com.jcl.recruit.core.config.SystemConfig;
import com.jcl.recruit.core.constants.Constants;
import com.jcl.recruit.login.vo.UserExternalLoginInfo;
import com.jcl.recruit.user.model.User;
import com.jcl.recruit.user.model.UserExternalAccess;
import com.jcl.recruit.user.service.UserService;
import com.jcl.recruit.wechat.service.WechatLoginService;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName WechatRegisterAndLoginController
 * @Description TODO
 * @Author yyliu
 * @Date 2018/9/14 10:21
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/wechat")
public class WechatLoginController {

    private static final Logger logger = LoggerFactory.getLogger(WechatLoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private WechatLoginService wechatLoginService;

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 10:23 2018/9/14
     * @Param [request, response]
     * @return void
     **/
    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) {

        String token = request.getParameter("token");
        String userId = null;
        if (StringUtils.hasLength(token)) {
            UserToken userToken = SecurityUtils.decodeUserToken(token);
            userId = userToken.getUserId();
        }

        logger.info("request param userid is : {}", userId);
        if (StringUtils.hasLength(userId)) {
            User user = userService.findOneById(Integer.parseInt(userId));
            user = wechatLoginService.doLogin(user, SecurityUtils.FROM_WECHAT);
            try {
                String domain = SystemConfig.getSystemWebUrl();
                response.sendRedirect(domain + "/mb/mbindex.html#/?token=" + user.getToken());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /* *
     * @Author yyliu
     * @Description 微信登陆
     * @Date 19:46 2018/9/12
     * @Param [code, state, request, response]
     * @return void
     **/
    @RequestMapping("/access")
    public ApiResponse access(String code, String state) throws IOException {

        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
            return ApiResponse.error(Constants.ReturnInfo.ERROR_PARAM_NULL_MSG);
        }

        WechatUtils.AccessInfo accessInfo = new WechatUtils.AccessInfo();

        // 获取登录用户身份
        WechatUtils.WechatUserInfo userInfo = wechatLoginService.getWechatUserInfo(code);
        if (state.indexOf(WechatUtils.LOGIN_STATE) > -1) {
            UserExternalLoginInfo loginInfo = wechatLoginService.accessLogin(userInfo);

            User user = wechatLoginService.doLogin(loginInfo.getCorpCode(), loginInfo.getUserId(), SecurityUtils.FROM_WECHAT);
            accessInfo.setUserToken(user.getToken());
            accessInfo.setUserStatus(user.getStatus());
            accessInfo.setState(WechatUtils.LOGIN_STATE);
            if (state.indexOf(WechatUtils.LOGIN_STATE_CRAWLER_DOWNLOAD) > -1) {
                accessInfo.setRouterState(WechatUtils.LOGIN_STATE_CRAWLER_DOWNLOAD);
            }

        } else if (state.indexOf(WechatUtils.LOGIN_STATE_INVITE) > -1) {

            String accessKey = state.split(WechatUtils.LOGIN_STATE_SPLIT)[1];
            WechatUtils.AccessLoginInfo loginInfo = wechatLoginService.accessLoginByInvite(userInfo, accessKey);
            accessInfo.setMsg("操作成功");
            if ("login".equals(loginInfo.getCode())) {
                User user = loginInfo.getUser();
                if (Constants.UserInfo.USER_STATUS_UNACTIVE == user.getStatus()) {
                    user = wechatLoginService.permissAlert(user);
                } else {
                    user = wechatLoginService.doLogin(user, SecurityUtils.FROM_WECHAT);
                }
                accessInfo.setUserStatus(user.getStatus());
                accessInfo.setUserToken(user.getToken());
            } else if ("register".equals(loginInfo.getCode())) {
                // 跳转页面 完善注册信息
                logger.info("register userjoin  !!!");
                UserExternalAccess userAccess = loginInfo.getUserExternalAccess();
                accessInfo.setAccessId(userAccess.getId().toString());
                accessInfo.setAccessKey(accessKey);
            } else {
                accessInfo.setMsg(loginInfo.getMsg());
            }

            accessInfo.setState(WechatUtils.LOGIN_STATE_INVITE);
            accessInfo.setCode(loginInfo.getCode());
        }

        return ApiResponse.success(accessInfo);
    }
}
